<script setup>
import { reactive, ref } from 'vue';
import router from '@/router';
import loginApi from '../api/login_api.js';
import {
  Stamp, SwitchButton, Expand, Fold, Menu, Suitcase,
  Goods, Document, Calendar, UserFilled, List, Setting
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const activeIndex = ref('1')

const userInfo = ref({});

// 取出当前登录用户的信息
const loginAdmin = ref({
  name: "未登录",
});
getLoginAdmin();

// 密码重置相关
const resetPasswordDialog = ref(false);
const passwordForm = ref({
  newPassword: '',
  confirmPassword: ''
});

// 邮箱验证相关
const emailDialog = ref(false);
const emailForm = ref({
  email: '',
  verificationCode: ''
});
const isSendingCode = ref(false);
const codeCountdown = ref(0);

// 菜单  用户管理， 分类管理， 商品管理
const menuData = ref([
  {name: '首页', icon: 'Menu', children:  [
      {name: '欢迎', icon: 'welcome', path: "/welcome"},
    ]},
  {name: '品牌管理', icon: 'Menu', children: [
      {name: '品牌列表', icon: 'Suitcase', path:"/brand"},
    ]},
  {name: '产品管理', icon: 'Menu', children: [
      {name: '产品列表', icon: 'Goods', path: "/product"},
    ]},
  {name: '尺码管理', icon: 'Menu', children: [
      {name: '尺码', icon: 'Calendar', path: "/size"},
    ]},
  {name: '图案管理', icon: 'Menu', children: [
      {name: '图案', icon: 'UserFilled', path: "/pattern"},
    ]},
  {name: '衣服分类', icon: 'Menu', children: [
      {name: '种类', icon: 'List', path: "/category"},
    ]},
  {name: '尺码与库存', icon: 'Menu', children: [
      {name: '列表', icon: 'Setting', path: "/product_size"},
    ]},
  {name: '数据统计', icon: 'Menu', children: [
      {name: '图表展示', icon: 'Setting', path: "/charts"},
    ]},

]);

async function getLoginAdmin(){
  let token=localStorage.getItem("token");
  if(!token){
    //跳转到登录页面
    router.push("/login")
  }
  const res=await loginApi.getloginbean();
  loginAdmin.value=res;
}

// 发送验证码
async function sendVerificationCode() {
  if (!emailForm.value) {
    ElMessage.error('请输入邮箱');
    return;
  }

  // 简单的邮箱格式验证
  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailReg.test(emailForm.value.email)) {
    ElMessage.error('请输入有效的邮箱地址');
    return;
  }

  try {
    isSendingCode.value = true;
    // 调用后端发送验证码的API
    /*console.log(emailForm.value.email);*/
    const res = await loginApi.sendVerificationCode(emailForm.value);
    ElMessage.success('验证码已发送，请查收');

    // 开始倒计时
    codeCountdown.value = 60;
    const countdownTimer = setInterval(() => {
      codeCountdown.value--;
      if (codeCountdown.value <= 0) {
        clearInterval(countdownTimer);
        isSendingCode.value = false;
      }
    }, 1000);
  } catch (error) {
    ElMessage.error('发送验证码失败，请重试');
    isSendingCode.value = false;
    console.error(error);
  }
}

// 验证验证码
async function verifyCode() {
  if (!emailForm.value.email) {
    ElMessage.error('请输入邮箱');
    return;
  }

  if (!emailForm.value.verificationCode) {
    ElMessage.error('请输入验证码');
    return;
  }

  try {
    // 调用后端验证验证码的API
    const res = await loginApi.verifyCode({
      email: emailForm.value.email,
      code: emailForm.value.verificationCode
    });
    console.log("原始返回结果:", res);
    if (res) {
      ElMessage.success('验证码验证成功');
      emailDialog.value = false;
      // 打开重置密码弹窗
      resetPasswordDialog.value = true;
    } else {
      ElMessage.error('验证码不正确或已过期');
    }
  } catch (error) {
    ElMessage.error('验证失败，请重试');
    console.error(error);
  }
}

async function submitResetPassword(){
  // 表单验证
  if (!passwordForm.value.newPassword) {
    ElMessage.error('请输入新密码');
    return;
  }

  if (passwordForm.value.newPassword.length < 6) {
    ElMessage.error('新密码长度不能少于6位');
    return;
  }

  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    ElMessage.error('两次输入的新密码不一致');
    return;
  }
  if (!loginAdmin.value.member) {
    ElMessage.error('无法获取用户标识，请重新登录');
    return;
  }

  const params = {
    member: loginAdmin.value.member,
    Password: passwordForm.value.newPassword,
    email: emailForm.value.email // 增加邮箱参数，用于后端验证
  };
  try {
    // 调用API重置密码
    const res = await loginApi.resetpassword(params);
    ElMessage.success('密码重置成功，请重新登录');
    resetPasswordDialog.value = false;
    logout(); // 重置成功后退出登录
  } catch (error) {
    ElMessage.error('网络错误，重置密码失败');
    console.error(error);
  }
}

//用户下拉菜单的点击
function handleSelect(key, keyPath){
  if (key == 'logout'){
    // 用户退出
    logout();
  }
  if (key == 'resetpassword'){
    // 重置密码，先打开邮箱验证
    resetPassword();
  }
}

// 左侧菜单动作
function handleMenu(key){
  if (key){
    router.push(key);
  }
}

// 退出
function logout(){
  localStorage.removeItem("token");
  router.push('/login')
}

// 重置密码 - 先打开邮箱验证弹窗
function resetPassword(){
  emailDialog.value = true;
  // 重置邮箱表单
  emailForm.value = {
    email: '',
    verificationCode: ''
  };
  codeCountdown.value = 0;
  isSendingCode.value = false;
}

// 左侧菜单展开折叠
const isCollapse = ref(false);
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-menu :default-active="activeIndex"
                 class="el-menu-demo"
                 mode="horizontal"
                 :ellipsis="false"
                 background-color="#f3f7ff"
                 text-color="#393939"
                 active-text-color="#ffd04b"
                 @select="handleSelect">

          <el-menu-item index="0">
            <img style="height: 80%" src="@/assets/logo.png" alt="易视界" />
            <span style="padding-left: 50px; font-size: 24px; color:#393939;">尚品服饰-管理系统</span>
          </el-menu-item>
          <div class="flex-grow" />
          <el-sub-menu index="1">
            <template #title>
              <el-icon><Stamp></Stamp></el-icon>
              {{ loginAdmin?loginAdmin.member:'没登录' }}
            </template>
<!--            <el-menu-item index="logout">修改信息</el-menu-item>-->
            <el-menu-item index="resetpassword">重置密码</el-menu-item>
            <el-menu-item index="logout">退出
              <el-icon><SwitchButton></SwitchButton></el-icon>
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-header>
      <el-container>
        <el-aside :width="1">
          <div style="height: 60px;line-height: 60px; text-align: right; color: #e1d0d0; font-size: 20px; margin-right: 24px;">
            <el-icon @click="isCollapse=!isCollapse">
              <Expand v-if="isCollapse"></Expand>
              <Fold v-else></Fold>
            </el-icon>
          </div>
          <el-menu active-text-color="#ffd04b" background-color="#0c1d40" class="el-menu-vertical-demo"
                   default-active="/charts" text-color="#fff" :collapse="isCollapse"
                   @select="handleMenu">
            <!-- 动态生成菜单 -->
            <el-sub-menu v-for="(menu, index) in menuData" :index="index.toString()">
              <template #title>
                <component
                    class="icons"
                    :is="menu.icon"
                    style="width: 1em; height: 1em; margin-right: 8px" >
                </component>
                <span>{{ menu.name }}</span>
              </template>
              <el-menu-item v-for="(child, ind) in menu.children" :index="child.path">
                <el-icon><component :is="child.icon"></component></el-icon>
                <span>{{ child.name }}</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>

    <!-- 邮箱验证和验证码弹窗 -->
    <el-dialog
        title="验证邮箱"
        v-model="emailDialog"
        width="30%"
    >
      <el-form :model="emailForm" label-width="100px">
        <el-form-item label="邮箱账号">
          <el-input
              v-model="emailForm.email"
              placeholder="请输入您的邮箱"
              :disabled="codeCountdown > 0"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码">
          <el-row :gutter="10">
            <el-col :span="14">
              <el-input
                  v-model="emailForm.verificationCode"
                  placeholder="请输入验证码"
              ></el-input>
            </el-col>
            <el-col :span="10">
              <el-button
                  type="primary"
                  @click="sendVerificationCode"
                  :disabled="isSendingCode || codeCountdown > 0"
              >
                {{ codeCountdown > 0 ? `${codeCountdown}秒后重发` : '发送验证码' }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="emailDialog = false">取消</el-button>
        <el-button type="primary" @click="verifyCode">验证并继续</el-button>
      </template>
    </el-dialog>

    <!-- 重置密码弹窗 -->
    <el-dialog
        title="重置密码"
        v-model="resetPasswordDialog"
        width="30%"
    >
      <el-form :model="passwordForm" label-width="100px">
        <el-form-item label="新密码">
          <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="submitResetPassword">确认重置</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style>
.flex-grow {
  flex-grow: 1;
}

.common-layout,
.el-container {
  height: 100%;
}

.el-header {
  --el-header-padding: 0;
  --el-header-height: 80px;
  box-sizing: border-box;
  flex-shrink: 0;
  height: var(--el-header-height);
  padding: var(--el-header-padding);
}

.el-menu--horizontal {
  height: 80px;
}

.el-aside {
  background-color: #0c1d40;
}

.el-main{
  padding: 0px;
}

.el-menu{
  border-width: 0px;
}
.el-menu-item{
  font-size: 16px;
}
.el-menu-demo{
  box-shadow: 0 2px 4px rgba(0,0,0,0.25);
}

.el-sub-menu__title{
  font-size: 16px;
}
</style>
